<?php

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;


// 保存微信头像到本地存储
function saveWeixinAvatar($avatarUrl)
{
    try {
        // 下载头像
        $response = Http::timeout(10)->get($avatarUrl);
        if (!$response->successful()) {
            throw new \Exception('下载微信头像失败');
        }

        // 生成唯一文件名
        $filename = 'images/' . Str::random(20) . '.jpg';

        // 保存到 storage/app/public
        Storage::disk('public')->put($filename, $response->body());

        // 返回相对路径
        return $filename;

    } catch (\Exception $e) {
        // 使用默认头像
        return '';
    }
}

function createSn($prefix = '', $rand_suffix_length = 4, $pool = [])
{
    $suffix = '';
    for ($i = 0; $i < $rand_suffix_length; $i++) {
        if (empty($pool)) {
            $suffix .= rand(0, 9);
        } else {
            $suffix .= $pool[array_rand($pool)];
        }
    }
    $sn = $prefix . date('YmdHis') . $suffix;
    return $sn;
}
